package com.boarsoft.boar.soagov.batch.health;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.boar.entity.AppInst;
import com.boarsoft.boar.service.AppInstService;
import com.boarsoft.flow.core.bean.ForkHandler;

/**
 * 并行检测N个实例
 * 
 * @author Mac_J
 *
 */
public class HealthChkAppInstFH implements ForkHandler {
	private static final Logger log = LoggerFactory.getLogger(HealthChkAppInstFH.class);

	@Autowired
	protected AppInstService appInstSvc;

	/** 最多线程数 */
	protected int maxThreads = 5;

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> fork(String key, Object data, Throwable throwable) {
		Map<String, Object> rm = new HashMap<>();
		List<Map<String, Object>> pLt = (List<Map<String, Object>>) data;
		//TODO 此循环有问题
		for (Map<String, Object> map : pLt) {
			String appId = (String) map.get("appId");
			String handler = (String) map.get("handler");
			String env = (String) map.get("env");
			String group = (String) map.get("group");
			List<AppInst> sLt = appInstSvc.list(env, appId, group, null);
			int i = 0, j = 0, //
					tt = sLt.size(), // 总实例数
					ts = Math.min(tt, maxThreads); // 最大线程数
			List<Map<String, Object>> lt = null;
			for (AppInst s : sLt) {
				if (i++ % ts == 0) {
					lt = new ArrayList<>();
					rm.put(String.valueOf(j++), lt);
				}
				Map<String, Object> m = new HashMap<>();
				m.put("handler", handler);
				m.put("addr", s.getAddr());
				lt.add(m);
			}
		}
		log.info("Fork result = {}", rm);
		return rm;
	}

	public int getMaxThreads() {
		return maxThreads;
	}

	public void setMaxThreads(int maxThreads) {
		this.maxThreads = maxThreads;
	}
}